<?php
namespace app\backend\controller;

use app\backend\model\Menu as MenuModel;
use app\backend\model\Tab as TabModel;
use app\backend\model\Other as OtherModel;
use think\Db;
use think\Db\Query;
use think\Request;
use app\backend\org\Helper;

class Modules extends Base
{
    // 模块分类列表展示
    public function index()
    {
        $model = new MenuModel;
        // 获取分页显示
        $result = $model->getAll()->paginate(5);
        $page = $result->render();
        $this->assign('page',$page);
        $this->assign('modules',$result);
        $this->assign('empty',"暂无数据");
        $this->assign('act','index');//高亮js
        return $this->fetch();

    }

    //新建模块分类
    public function modules_create(){
        if (Request::instance()->isPost())
        {
            $model = new MenuModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
           // die();
            // 判断已有内容不能重复新增去修改
            $name = Db::query("select menu_id,menu_name_cn,p_id from ls_menu where `menu_name_cn`='".$post['menu_name_cn']."' and `p_id`='".$post['p_id']."' and delete_time is NULL ");
            //var_dump($name);exit;
            if(!empty($name)){
                return $this->redirect(url('modules_update',array('id'=>$name[0]['menu_id'])));
            }
            //手动排序
            $maual_sort = Db::query("select sort from ls_menu where p_id=1 and delete_time is null");
            //sort函数 排序 [0]最小值
            if (!empty($maual_sort)){
                sort($maual_sort);
                //最大值
                $max = $maual_sort[count($maual_sort)-1];
                $post["sort"]= $max["sort"]+1;
            }else{
                $post["sort"]=1;
            }

            //var_dump($post["sort"]);exit;
            // 验证表单并插入数据库
            $result = $this->validate($post,'Modules.add');
            if(true !== $result){
                // 验证失败 输出错误信息
                dump($result);
                return $this->error($msg = '参数错误，验证失败');
            }

            // 登录人的ID
            $post["creator_id"] = \think\Session::get('login_id');
            //$model->insert($post);

            // 跳转到显示页面
            // 插入数据库后修改数据库跳转连接
            $line = $model->save($post);
            //var_dump($model);
            //var_dump($line);die();
            if(!$line){
               return $this->error($this->update_error);
            } else {
            //menu路径以及menu对应menu表的id
               MenuModel::update(["menu_url"=>"/backend/modules/tab/id/".$model['menu_id'],"urlflag"=>1],["menu_id"=>$model["menu_id"]]);
                //$this->assign('url',$url);
                //var_dump($aa);exit;
               return $this->redirect('modules/index');
            }
        };

        //查询某个分类的直接子类id和名字
        $imchild=MenuModel::where(["menu_name_cn"=>"模块管理"])->value("menu_id");
        $this->assign('p_id',$imchild);

        $this->assign('act','modules/index');
        return $this->fetch();
    }

    //模块分类修改
    public function modules_update($id)
    {
        if (Request::instance()->isPost())
        {
            $model = new MenuModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
            $post["content_cn"]=preg_replace('/<p class="main-title"><br\/><\/p>/','<p class="main-title"></p>',$post["content_cn"]);
            $post["content_en"]=preg_replace('/<p class="main-title"><br\/><\/p>/','<p class="main-title"></p>',$post["content_en"]);
            //var_dump($post["content_cn"]);exit;
            //var_dump($post);exit;
            //新建变量存放other表内容
            $other = [];
            $other["p_id"] = $post["id"];
            $other["title_cn"] = $post["menu_name_cn"];
            $other["title_en"] = $post["menu_name_en"];
            $other["content_cn"] = $post["content_cn"];
            $other["content_en"] = $post["content_en"];
            $content_en = addslashes($other["content_en"]);

            // 判断other表已有内容不能重复新增去修改
            $name = Db::query("select other_id,content_cn,content_en,p_id from ls_other where `title_cn`='".$other['title_cn']."' or `p_id`='".$other['p_id']."' and delete_time is NULL ");

            //var_dump($name);exit;
            if(!empty($name)){
                $update_other = Db::execute("update ls_other set title_cn='{$other['title_cn']}',title_en=\"{$other['title_en']}\",content_cn='{$other['content_cn']}',content_en=\"{$content_en}\" where other_id = '{$name[0]['other_id']}' ");
                //$update_other = addslashes($update1);
                //var_dump($update_other);exit;
                //return $this->redirect(url('modules_update',array('id'=>$id)));
                if(!$update_other){
                    // 验证失败 输出错误信息
                    dump($update_other);
                    return $this->error($msg = 'other表修改失败');
                }
            }else{
                //插入other数据表
                $other_con = $this->validate($other,'Other.edit');
                if(true !== $other_con){
                    // 验证失败 输出错误信息
                    dump($other_con);
                    return $this->error($msg = '参数错误，验证失败');
                }
                // 登录人的ID
                $post["creator_id"] = \think\Session::get('login_id');
                $other["creator_id"] = $post["creator_id"];
                //$model->insert($post);
                // 过滤掉OTHER表中没有的字段，保存
                $otherM = new OtherModel;
                $line = $otherM->allowField(true)->save($other);
                if(!$line){
                    return $this->error($this->update_error);
                }
            }


            //验证表单并插入数据库
            $result = $this->validate($post,'Modules.edit');
            if(!$result){
                $this->error($result->getError());
            }
            // 过滤掉数据表中没有的字段，保存
            $result = $model->allowField(true)->save($post,['menu_id'=>$id]);
            //针对全时全程
            $full = Db::query("select menu_id,p_id,menu_name_cn from ls_menu where menu_id=$id and p_id not in(0,1) and delete_time is null ");
            //var_dump($full);exit;
            if(!empty($full)){
                //echo 123;
                $menu_id = Request::instance()->param("menu_id");
                //var_dump($menu_id);exit;
                if(false === $result){
                    $this->error($this->update_error);
                } else {
                    $this->success('修改成功',url('modules/tab',["id"=>$menu_id]));
                }
            }else{
                if(false === $result){
                    $this->error($this->update_error);
                } else {
                    $this->success('修改成功','modules/index');
                }
            }
        }

        $menu_id = Request::instance()->param("menu_id");
        $this->assign('menu_id', $menu_id);

        $p_id = Db::query("select other_id from ls_other where p_id=$id and delete_time is null");
        //var_dump($p_id);exit;
        //根据主键插记录
        $record = MenuModel::get($id);
       // $record["content_cn"]=preg_replace('/[\r\n]/','',$record["content_cn"]);
        //$record["content_en"]=preg_replace('/[\r\n]/','',$record["content_en"]);
        //新建other
        if(!empty($p_id[0]["other_id"])){
            $record2 = OtherModel::get($p_id[0]["other_id"]);
            $this->assign('other', $record2);
        }else{
            $record2["content_cn"] = "";
            $record2["content_en"] = "";
            $this->assign('other', $record2);
        }
        //var_dump($record2);exit;
        $this->assign('id',$id);
        $this->assign('modules', $record);

        $this->assign('act','index');
        return $this->fetch();
    }

    //删除模块分类  软删除，记录删除时间
    public function modules_delete($id)
    {
        $menu_p = Db::query("select menu_id,p_id,menu_name_cn from ls_menu where `p_id`=$id and delete_time is null ");
        $tab_p = Db::query("select tab_id,p_id,tab_name_cn from ls_tab where `p_id`=$id and delete_time is null ");
        //针对全时全程
        if(!empty($menu_p)){
            $this->error("该分类下有子类，请先删除子类");
        }else{
            MenuModel::destroy($id);//软删除
            //AlltimeModel::destroy($id,true);//真实删除

            $menu_id = Request::instance()->param("menu_id");
            $this->redirect('modules/tab',["id"=>$menu_id]);
        }

        if(!empty($tab_p)){
            $this->error("该分类下有子类，请先删除子类");
        }else{
            MenuModel::destroy($id);//软删除
            //AlltimeModel::destroy($id,true);//真实删除

            $menu_id = Request::instance()->param("menu_id");
            $this->redirect('modules/index',["id"=>$menu_id]);
        }
        //var_dump($tab_p);exit;
        return $this->fetch();
    }


    //tab列表展示
    public function tab($id=0){
        $model = new TabModel;
        //var_dump($model);exit;
        //获取分类标题
        $model2 = new MenuModel;
        $title = $model2->where(["menu_id"=>"$id"])->value("menu_name_cn");
        //echo "<pre>";
        //print_r($title);exit;
        // 获取分页显示
        $p_id=TabModel::where(["p_id"=>"$id"])->value("tab_id");
        //$this->assign('p_id',$imchild);
        $menu_p = $model2->where(["p_id"=>"$id"])->value("menu_id");
        $tab = TabModel::where(["delete_time"=>array('exp','is null')])->select();
        //echo "<pre>";
        //print_r($tab);exit;
        if(isset($menu_p)){
            //$re2 = $model2->menu_2($id)->paginate(5);
            $re2 = Db::query("select menu_id,p_id,menu_name_cn,menu_name_en from ls_menu where `delete_time` is null and `p_id`={$id} order by sort ASC");
           // echo "<pre>";
           // print_r($tab);exit;
            //循环拼接menu and tab全时全程康新源
            foreach($re2 as $k=>$v){
                foreach ($tab as $a=>$b){
                    if($v["menu_id"]==$b["p_id"]){
                        if (isset($re2[$k]["child"])) {
                            $re2[$k]["child"][] = $b;
                        } else {
                            $re2[$k]["child"] = [$b];
                        }
                    }
                }
            }
            //echo "<pre>";
            //print_r($re2);exit;
            $this->assign("menu_2",$re2);
        }
        $this->assign('menu_id',$id);
        $result = $model->getAll($id)->paginate(5);
        $page = $result->render();
        $this->assign('p_id',$p_id);
        $this->assign('page',$page);
        $this->assign('title',$title);
        $this->assign('tab',$result);
        //$this->assign('empty',"暂无数据");
        $this->assign('act','index');//高亮js
        return $this->fetch();
    }

    //tab新建子分类
    public function tab_create(){
        $full_name = "领星产品";
           if (Request::instance()->isPost())
        {
            $model = new TabModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
            //释放数据库不存在字段
            unset($post["full_id"]);
            //var_dump( $post);exit;

//全时全程下面内容添加到menu表
            $fulltime = Db::query("select menu_id,p_id,menu_name_cn,menu_name_en from ls_menu where `delete_time` is null and `menu_name_cn`='{$full_name}'");
            if($post["p_id"]==$fulltime[0]["menu_id"]){
                //手动排序
                $maual_sort = Db::query("select sort from ls_menu where p_id={$fulltime[0]["menu_id"]} and  delete_time is null");

                if(!empty($maual_sort)){
                    //sort函数 排序 [0]最小值
                    sort($maual_sort);
                    //最大值
                    $max = $maual_sort[count($maual_sort)-1];
                    $post["sort"]= $max["sort"]+1;
                }else{
                    $post["sort"]= 1;
                }

                //var_dump($post["sort"]);exit;
                unset($post["tab_name_cn"]);
                unset($post["tab_name_en"]);
                $result1 = $this->validate($post,'Modules.add');
                if(true !== $result1){
                    // 验证失败 输出错误信息
                    dump($result1);
                    return $this->error($msg = '参数错误，验证失败');
                }

                $model2 = new MenuModel();
                // 插入数据库后修改数据库跳转连接
                $line = $model2->save($post);
                //获取url中menu_id
                $menu_id = Request::instance()->param("menu_id");
                if(!$line){
                    return $this->error($this->update_error);
                } else {
                    //tab路径对应tab_id
                    MenuModel::update(["menu_url"=>"/backend/modules/tab/id/".$model2['menu_id'],"urlflag"=>0],["menu_id"=>$model2["menu_id"]]);
                    //$id  = $record["p_id"];
                    return $this->redirect('modules/tab',["id"=>$menu_id]);
                }
            }else{
                unset($post["menu_name_cn"]);
                unset($post["menu_name_en"]);
                // 判断已有内容不能重复新增去修改
                $name = Db::query("select tab_id,tab_name_cn,p_id from ls_tab where `tab_name_cn`='".$post['tab_name_cn']."' and `p_id`='".$post['p_id']."' and delete_time is NULL ");
                //var_dump($name);exit;
                if(!empty($name)){
                    return $this->redirect(url('tab_update',array('id'=>$name[0]['tab_id'])));
                }
                //手动排序
                $maual_sort = Db::query("select sort from ls_tab where p_id='".$post['p_id']."' and  delete_time is null");
                //sort函数 排序 [0]最小值
                if($maual_sort){
                    sort($maual_sort);
                    $max = $maual_sort[count($maual_sort)-1];
                    $post["sort"]= $max["sort"]+1;
                }else{
                    $max = 1;
                    $post["sort"] = 1;
                }

                //最大值

               // var_dump( $post["sort"]);exit;
                // 验证表单并插入数据库
                $result = $this->validate($post,'Tabs.add');
                if(true !== $result){
                    // 验证失败 输出错误信息
                    dump($result);
                    return $this->error($msg = '参数错误，验证失败');
                }
                // 插入数据库后修改数据库跳转连接
                $line = $model->save($post);
                $menu_id = Request::instance()->param("menu_id");
                if(!$line){
                    return $this->error($this->update_error);
                } else {
                    //tab路径对应tab_id
                    TabModel::update(["tab_url"=>"modules/list/id/".$model['tab_id']],["tab_id"=>$model["tab_id"]]);
                    //$id  = $record["p_id"];
                    return $this->redirect('modules/tab',["id"=>$menu_id]);
                }
            }
            // 登录人的ID
            $post["creator_id"] = \think\Session::get('login_id');
        }

        //url中menu_id的值
        $menu_id = Request::instance()->param("menu_id");
        //URL中tab_id的值
        $id = Request::instance()->param("id");
        //var_dump($id);exit();
        if(isset($id)){
            $this->assign('p_id',$id);
        }else{
            $this->assign('p_id',$menu_id);
        }

        //页面模板menu_id
        $this->assign('menu_id',$menu_id);
        $type=MenuModel::where(["menu_id"=>$menu_id])->value("menu_name_cn");
        //添加分类的标题
        $this->assign('menu_name_cn',$type);

        //全时全程的ID
        $fulltime1 = Db::query("select menu_id,p_id,menu_name_cn,menu_name_en from ls_menu where `menu_name_cn`='{$full_name}' and  `delete_time` is null ");
        //var_dump($fulltime1);exit;
        $this->assign('full_id',$fulltime1[0]['menu_id']);
        $this->assign('act','index');
        return $this->fetch();
    }

    public function tab_update($id){

        if (Request::instance()->isPost())
        {
            $model = new TabModel;
            $post = Request::instance()->post();// 获取经过过滤的全部post变量
            //验证表单并插入数据库
            $result = $this->validate($post,'Tabs.edit');
            if(!$result){
                $this->error($result->getError());
            }
            // 过滤掉数据表中没有的字段，保存
            $result = $model->allowField(true)->save($post,['tab_id'=>$id]);
            //var_dump($menu_id);exit;
            //echo $result;exit;
            $menu_id = Request::instance()->param("menu_id");
            if(false === $result){
                $this->error($this->update_error);
            } else {
                $this->success('修改成功',url('modules/tab',["id"=>$menu_id]));
            }
        }

        $menu_id = Request::instance()->param("menu_id");
        $type=TabModel::where(["tab_id"=>$id])->value("tab_name_cn");
        //添加分类的标题
        $this->assign('tab_name_cn',$type);
        //根据主键插记录
        $record = TabModel::get($id);
        //var_dump($record);exit;

        $this->assign('id',$id);
        $this->assign('menu_id',$menu_id);
        $this->assign('tab', $record);
        $this->assign('act','index');
        return $this->fetch();
    }

    //删除模块分类  软删除，记录删除时间
    public function tab_delete($id)
    {
        $list_p = Db::query("select list_id,p_id,list_title_cn from ls_list where `p_id`=$id and delete_time is null ");
        if(!empty($list_p)){
            $this->error("该分类下有文章或新闻，请先删除其内容");
        }else{
            TabModel::destroy($id);//软删除
            //AlltimeModel::destroy($id,true);//真实删除

            $menu_id = Request::instance()->param("menu_id");
            $this->redirect('modules/tab',["id"=>$menu_id]);
        }
        return $this->fetch();
    }
}